package com.work.studio;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Toast;

import com.work.studio.constracts.MainContract;
import com.work.studio.dialogs.UpgradeDialog;
import com.work.studio.entitys.AttendanceStatisticsEntity;
import com.work.studio.entitys.BaseApiEntity;
import com.work.studio.entitys.CustomerEntity;
import com.work.studio.entitys.CustomerSignEntity;
import com.work.studio.entitys.CustomerVisitRntity;
import com.work.studio.entitys.DailyFinishEntity;
import com.work.studio.entitys.RankingEntity;
import com.work.studio.entitys.UpdateAppEntity;
import com.work.studio.net.ConsumerMy;
import com.work.studio.net.NetManager;
import com.work.studio.presenters.MainPresenter;
import com.work.studio.utils.AppUtils;
import com.work.studio.utils.DownloadUtil;
import com.work.studio.utils.SPUtils;
import com.work.studio.views.AppDownLoadManager;
import com.work.studio.views.CustomerVisitorViews;
import com.work.studio.views.DataStatisticsViews;
import com.work.studio.views.MainView;

import java.io.File;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MainActivity extends AppCompatActivity implements MainContract.View {


    private CustomerVisitorViews customerVisitorViews;
    private DataStatisticsViews dataStatisticsViews;
    private MainPresenter presenter;
    private MainView mainView;
    private UpdateAppEntity updateAppEntity;
    private String TAG = this.getClass().getSimpleName();
    private UpgradeDialog dialog;
    private File file = null;
    public final int GET_UNKNOWN_APP_SOURCES = 12;
    public final int INSTALL_APK_REQUESTCODE = 11;
    public final int EXTERNAL_STORAGE_REQ_CODE = 10;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        presenter = new MainPresenter(this);
        customerVisitorViews = this.findViewById(R.id.customer_visitor_views);
        mainView = this.findViewById(R.id.main_view);
        dataStatisticsViews = this.findViewById(R.id.data_statistics_views);
        mainView.onCreate(savedInstanceState);
    }

    @Override
    protected void onDestroy() {
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        mainView.onDestroy();
        super.onDestroy();
    }

    @Override
    protected void onResume() {

        mainView.init();

        if (presenter != null) {
            presenter.checkPermission(this);
        }

        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        mainView.onResume();

    }
//
//    @RequiresApi(api = Build.VERSION_CODES.M)
//    protected void askPermissions() {
//        String[] permissions = {
//                "android.permission.READ_EXTERNAL_STORAGE",
//                "android.permission.WRITE_EXTERNAL_STORAGE"
//        };
//        int requestCode = 200;
//        requestPermissions(permissions, requestCode);
//    }
//
//    @Override
//    public boolean shouldShowRequestPermissionRationale(@NonNull String permission) {
//
//        return super.shouldShowRequestPermissionRationale(permission);
//    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mainView.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mainView.onSaveInstanceState(outState);
    }

    @Override
    protected void onStop() {
        if (presenter != null) {
            presenter.stopPool();
        }
        super.onStop();
    }

    @Override
    public void onTimePool() {

        mainView.init();

    }



    /**
     * 客户拜访次数日统计
     */
    @Override
    public void onCustomerVisitorSuccess(List<CustomerVisitRntity> customerVisitRntities) {
        if (dataStatisticsViews != null) {
            dataStatisticsViews.setBarChart(customerVisitRntities);
        }
    }

    @Override
    public void onCustomerRecycle(List<CustomerSignEntity.CustomerReturnListBean> customerReturnListBeans) {
//        if (customerVisitorViews != null) {
//            customerVisitorViews.setVistorList(customerReturnListBeans);
//        }
    }

    /**
     * 考勤缺勤统计成功
     * @param attendanceStatisticsEntity
     */
    @Override
    public void onTodaySuccess(AttendanceStatisticsEntity attendanceStatisticsEntity) {

        try {

            if (dataStatisticsViews != null) {
                dataStatisticsViews.setPieToday(attendanceStatisticsEntity);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 日报完成率
     * @param content
     */
    @Override
    public void onFinishSuccess(DailyFinishEntity content) {

        if (dataStatisticsViews != null) {
            dataStatisticsViews.setPieChartDatas(content);
        }
    }

    @Override
    public void permissionSuc() {
        requestVersion();
    }

    @Override
    public Context getContext() {
        return getApplicationContext();
    }

    @Override
    public void onRequestCustomer(CustomerEntity customerEntity) {
        if (customerVisitorViews != null) {
            customerVisitorViews.setVistorListT(customerEntity);
        }
    }

    /**
     * 获取某月份客户拜访客户排行榜
     * @param rankingEntities
     */
    @Override
    public void onRankingSuccess(List<RankingEntity> rankingEntities) {

        if (dataStatisticsViews != null) {
            dataStatisticsViews.setRanking(rankingEntities);
        }
    }

    /**
     * 地图数据
     * @param customerReturnList
     */
    @Override
    public void onMapViewDatas(List<CustomerSignEntity.CustomerReturnListBean> customerReturnList) {

        if (mainView != null) {
            mainView.setDatas(customerReturnList);
        }
    }



    private void requestVersion() {

        try {

            NetManager.getNet()
                    .requestVersion()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new ConsumerMy<BaseApiEntity<UpdateAppEntity>>() {
                        @Override
                        protected void _onSuccess(BaseApiEntity<UpdateAppEntity> menuEntity) {
                            super._onSuccess(menuEntity);
                            updateAppEntity = menuEntity.getContent();

                            int DataRefreshTimeSecond = updateAppEntity.getDataRefreshTimeSecond();
                            if (presenter != null) {
                                presenter.setDataRefreshTimeSecond(DataRefreshTimeSecond);
                            }
//                            SPUtils.putInt(getApplicationContext(), "DataRefreshTimeSecond", updateAppEntity.getDataRefreshTimeSecond());

                            presenter.initThreadPool(MainActivity.this);

                            checkVersion();
                        }

                        @Override
                        protected void _onError(String errorCode, String errorMessage) {
                            super._onError(errorCode, errorMessage);
                            presenter.initThreadPool(MainActivity.this);
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
            presenter.initThreadPool(MainActivity.this);
        }
    }

    /**
     * 检查应用版本信息
     */
    public void checkVersion() {

        try {

            if (updateAppEntity != null) {
                String appDownLoadUrl = updateAppEntity.getAppDownloadUrl();
                String appRemark = updateAppEntity.getAppRemark();
                String appVersion = updateAppEntity.getAppVersion();

                String currentVersionName = AppUtils.getVersionInfo(this);
                Log.e(TAG, "" + updateAppEntity.toString() + "  currentVersionName:" + currentVersionName);


                if (!TextUtils.isEmpty(appDownLoadUrl) && !TextUtils.isEmpty(appVersion) && !currentVersionName.equals(appVersion)) {
//                if (true) {
                    //升级

                    dismiss();

                    dialog = new UpgradeDialog(this)
                            .builder()
                            .setTitle("最新版本:V" + appVersion)
                            .setMsg("是否在线升级?")
                            .setCancleAble(false)
                            .setCanceledOnTouchOutside(false)
                            .setNeBtn("暂不升级", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {

                                    dismiss();
                                }
                            }).setPoBtn("在线升级", false, new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (dialog != null) {
                                        dialog.setPoBtn("正在下载");
                                        dialog.setPoBtnClick(false);
                                        dialog.setNeBtnName("后台下载");
                                        dialog.setNeBtnColor("#FF0000");
                                    }

//                                    path = Environment.getExternalStorageDirectory().getAbsolutePath();
//                                    int currentapiVersion = android.os.Build.VERSION.SDK_INT;
//                                    if (currentapiVersion >= 29) {
//                                        path = MainActivity.this.getExternalCacheDir().getAbsolutePath();
//                                    }


                                    String path = presenter.getDefaultFileCompressDirectory().getAbsolutePath();

                                        new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            //"http://static.yingyonghui.com/apk/yyh/9999/ac.publish.yyh/30064511/com.yingyonghui.market_3237_30064511.apk"
                                            DownloadUtil.get().download(""+updateAppEntity.getAppDownloadUrl(), path , "JLCloudSalesmanTvApp.apk", new DownloadUtil.OnDownloadListener() {
                                                @Override
                                                public void onDownloadSuccess(File files) {

                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            dismiss();
//                                                            Toast.makeText(MainActivity.this, "下载成功", Toast.LENGTH_SHORT).show();
                                                            file = files;
                                                            downLoadSuccess(files.getAbsolutePath());//安装
                                                            Log.e(TAG, "onDownloadSuccess:"+files.getAbsolutePath());
                                                        }
                                                    });

                                                }

                                                @Override
                                                public void onDownloading(int progress) {
                                                    Log.e(TAG, "onDownloading:"+progress);

                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            if (dialog != null && dialog.isShow()) {
                                                                dialog.setMsg("当前已下载:" + progress + "%");
                                                            }

                                                            if (progress >= 100) {
                                                                dismiss();
                                                            }

                                                        }
                                                    });
                                                }

                                                @Override
                                                public void onDownloadFailed(Exception e) {

                                                    runOnUiThread(new Runnable() {
                                                        @Override
                                                        public void run() {
                                                            Log.e(TAG, "onDownloadFailed:"+e.getMessage());
                                                            dismiss();
                                                            Toast.makeText(MainActivity.this, "下载失败:"+e.getMessage(), Toast.LENGTH_LONG).show();
                                                        }
                                                    });

                                                }
                                            });
                                        }
                                    }).start();


//                                    AppDownLoadManager.getInstance(MainActivity.this)
//                                            .setDownUrl(appDownLoadUrl)
//                                            .startDown().setListener(MainActivity.this);
                                }
                            });

                    try {
                        dialog.show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void dismiss() {
        if (dialog != null && dialog.isShow()) {
            dialog.dismiss();
        }
        dialog = null;
    }

    /**
     * 通过隐式意图调用系统安装程序安装APK
     */
    public void installAPK(Context context, File file) {

        try {

            Intent intent = new Intent(Intent.ACTION_VIEW);
            // 由于没有在Activity环境下启动Activity,设置下面的标签
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
                //参数1 上下文, 参数2 Provider主机地址 和配置文件中保持一致   参数3  共享的文件
                Uri apkUri =
                        FileProvider.getUriForFile(context, "com.work.studio.fileprovider", file);
                //添加这一句表示对目标应用临时授权该Uri所代表的文件
                intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
            } else {
                intent.setDataAndType(Uri.fromFile(file),
                        "application/vnd.android.package-archive");
            }
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();

            Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
            Log.e(TAG, "installAPK:"+e.getMessage());
        }
    }

    private void downLoadSuccess(String path) {
        if (Build.VERSION.SDK_INT >= 26) {
            //来判断应用是否有权限安装apk
            boolean installAllowed = getPackageManager().canRequestPackageInstalls();
            //有权限
            if (installAllowed) {
                //安装apk
                installAPK(MainActivity.this, new File(path));
            } else {
                //无权限 申请权限
                androidx.core.app.ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.REQUEST_INSTALL_PACKAGES}, INSTALL_APK_REQUESTCODE);
            }
        } else {
            installAPK(MainActivity.this, new File(path));
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case EXTERNAL_STORAGE_REQ_CODE:
                // 如果请求被拒绝，那么通常grantResults数组为空
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //申请成功，进行相应操作
                    checkVersion();
                } else {
                    Toast.makeText(this, "权限申请失败", Toast.LENGTH_SHORT).show();
                    //申请失败，可以继续向用户解释。
                }
                break;
            case INSTALL_APK_REQUESTCODE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //申请成功，进行相应操作
                    if (file != null) {
                        installAPK(MainActivity.this, file);
                    }
                    //startDownLoad(downloadUrl);
                } else {

                    Uri packageURI = Uri.parse("package:"+getPackageName());
                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES,packageURI);
                    startActivityForResult(intent, GET_UNKNOWN_APP_SOURCES);
                    Toast.makeText(this, "权限申请失败，请到权限页面打开权限", Toast.LENGTH_SHORT).show();
                    //申请失败，可以继续向用户解释。
                }
                break;


        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        Log.e(TAG, "requestCode:"+requestCode+" - resultCode:"+resultCode);
        if (resultCode == Activity.RESULT_OK) {

            switch (requestCode) {
                case GET_UNKNOWN_APP_SOURCES:

                    if (file != null) {
                        installAPK(this, file);
                    }
                    break;
            }
        }


    }


    private int po = -1;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {

            case KeyEvent.KEYCODE_ENTER:     //确定键enter
            case KeyEvent.KEYCODE_DPAD_CENTER:
                Log.d(TAG,"enter--->");


                if (dialog != null && dialog.isShow()) {
                    if (po == -1) {

                    } else if (po == 0) {
                        dialog.getNeBtn().performClick();
                    } else if (po == 1) {

                        dialog.getPoBtn().performClick();
                    }
                }
                         break;

            case KeyEvent.KEYCODE_BACK:    //返回键
                Log.d(TAG,"back--->");

                dismiss();
                po = -1;

                finish();
                return true;   //这里由于break会退出，所以我们自己要处理掉 不返回上一层

            case KeyEvent.KEYCODE_SETTINGS: //设置键
                Log.d(TAG,"setting--->");

                break;

            case KeyEvent.KEYCODE_DPAD_DOWN:   //向下键

                /*    实际开发中有时候会触发两次，所以要判断一下按下时触发 ，松开按键时不触发
                 *    exp:KeyEvent.ACTION_UP
                 */
                if (event.getAction() == KeyEvent.ACTION_DOWN){

                    if (dialog != null && dialog.isShow()) {
                        dialog.setPosBtnColor("#FD4A2E");
                        dialog.setNeBtnColor("#2c79ed");
                        po = 0;
                    }

                    Log.d(TAG,"down--->");
                }

                break;

            case KeyEvent.KEYCODE_DPAD_UP:   //向上键
                Log.d(TAG,"up--->");
                if (dialog != null&& dialog.isShow()) {
                    dialog.setPosBtnColor("#2c79ed");
                    dialog.setNeBtnColor("#FD4A2E");
                    po = 1;
                }
                break;

            case     KeyEvent.KEYCODE_0:   //数字键0
                Log.d(TAG,"0--->");

                break;

            case KeyEvent.KEYCODE_DPAD_LEFT: //向左键

                Log.d(TAG,"left--->");

                if (dialog != null && dialog.isShow()) {
                    dialog.setPosBtnColor("#FD4A2E");
                    dialog.setNeBtnColor("#2c79ed");
                    po = 0;
                }
                break;

            case KeyEvent.KEYCODE_DPAD_RIGHT:  //向右键
                Log.d(TAG,"right--->");
                if (dialog != null && dialog.isShow()) {
                    dialog.setPosBtnColor("#2c79ed");
                    dialog.setNeBtnColor("#FD4A2E");
                    po = 1;
                }
                break;

            case KeyEvent.KEYCODE_INFO:    //info键
                Log.d(TAG,"info--->");

                break;

            case KeyEvent.KEYCODE_PAGE_DOWN:     //向上翻页键
            case KeyEvent.KEYCODE_MEDIA_NEXT:
                Log.d(TAG,"page down--->");

                break;


            case KeyEvent.KEYCODE_PAGE_UP:     //向下翻页键
            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
                Log.d(TAG,"page up--->");

                break;

            case KeyEvent.KEYCODE_VOLUME_UP:   //调大声音键
                Log.d(TAG,"voice up--->");

                break;

            case KeyEvent.KEYCODE_VOLUME_DOWN: //降低声音键
                Log.d(TAG,"voice down--->");

                break;
            case KeyEvent.KEYCODE_VOLUME_MUTE: //禁用声音
                Log.d(TAG,"voice mute--->");
                break;

            default:
                break;
        }

        return super.onKeyDown(keyCode, event);

    }
}